package link.chengguo.orangemall.service.fms.impl;

import link.chengguo.orangemall.enums.AllEnum;
import link.chengguo.orangemall.enums.WithdrawType;
import link.chengguo.orangemall.exception.BusinessMallException;
import link.chengguo.orangemall.fms.entity.FmsShopWithdraw;
import link.chengguo.orangemall.fms.mapper.FmsShopWithdrawMapper;
import link.chengguo.orangemall.fms.service.IFmsShopWithdrawService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import link.chengguo.orangemall.pay.service.PayService;
import link.chengguo.orangemall.sys.entity.SysUser;
import link.chengguo.orangemall.sys.service.ISysUserService;
import link.chengguo.orangemall.util.UserUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author yzb
 * @date 2020-02-10
 */
@Service
public class FmsShopWithdrawServiceImpl extends ServiceImpl
        <FmsShopWithdrawMapper, FmsShopWithdraw> implements IFmsShopWithdrawService {

    @Resource
    private FmsShopWithdrawMapper fmsShopWithdrawMapper;
    @Resource
    private BCryptPasswordEncoder passwordEncoder;
    @Resource
    private ISysUserService userService;
    @Resource
    private PayService payService;

    @Override
    public boolean withdrawVerify(Integer result, Long id,String pwd,String note) {
        if(UserUtils.getCurrentMember().getPlatform().equals(AllEnum.PlatformType.Tenant.code())){
            //判断密码是否正确
            SysUser user= UserUtils.getCurrentMember();
            SysUser user2=userService.getById(user.getId());
            if (!passwordEncoder.matches(pwd, user2.getPassword())) {
                throw new BusinessMallException("密码错误");
            }
            //修改审核结果
            FmsShopWithdraw shopWithdraw = fmsShopWithdrawMapper.selectById(id);
            if (shopWithdraw.getTransferResult()!=0){
                throw new RuntimeException("该申请已处理过，不能重复操作！");
            }
            shopWithdraw.setTransferResult(result);
            shopWithdraw.setUpdateTime(new Date());
            shopWithdraw.setTranferDesc(note);
            fmsShopWithdrawMapper.updateById(shopWithdraw);
            if (result==2){
                //拒绝，则结束
                return true;
            }
            //如果同意，则需要进行转账操作
            if (shopWithdraw.getTransferMethod() == WithdrawType.Ali.getValue()) {
                //支付宝转账,调试使用最低转账金额
                boolean rt = payService.transferByAli("0.1", shopWithdraw.getWithdrawAccount(),
                        shopWithdraw.getWithdrawName(), "华盛配送平台商家提现转账");
//            boolean rt=payService.transferByAli(shopWithdraw.getMoney().toString(),shopWithdraw.getWithdrawAccount(),
//                    shopWithdraw.getWithdrawName(),"华盛配送平台商家提现转账");
                if (rt == false) {
                    return false;
                }
            }
        }
        return true;
    }
}
